package com.project;


import com.project.servlet.AddServlet;
import com.project.servlet.AddUserServlet;
import com.project.servlet.FirstServlet;
import com.project.servlet.TwoServlet;
import org.apache.catalina.Context;
import org.apache.catalina.Wrapper;
import org.apache.catalina.startup.Tomcat;

import javax.servlet.Servlet;
import java.io.File;
import java.net.URL;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.List;

/**
 * 服务器启动类
 */
public class MainServer {
    public MainServer(){
        //创建tomcat对象
        Tomcat tomcat = new Tomcat();
        //设置启动端口
        tomcat.setPort(8088);
        //引导Http引擎
        tomcat.getConnector();

        //创建上下文
        Context context = tomcat.addContext("", null);

        try {
           List<Class> classList =  this.getPackageClasses("com.project.servlet");
           for(Class c : classList){
               if(c.isAnnotationPresent(ServletObj.class)){
                   ServletObj servletObj = (ServletObj)c.getAnnotation(ServletObj.class);
                   this.registerServlet(context, c, servletObj.url());
               }
           }

            //启动tomcat
            tomcat.start();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void registerServlet(Context context,Class servletClass,String urlPath) throws Exception {
        //注册servlet，第一个参数为上下文对象，第二个参数为servlet名称,第三个参数为servlet实现类对象
        Wrapper servlet = Tomcat.addServlet(context,
                servletClass.getSimpleName(),(Servlet)servletClass.newInstance());
        //表示容器启动就直接实例化servlet
        servlet.setLoadOnStartup(1);
        //配置servlet的请求路径
        servlet.addMapping(urlPath);
    }

    public  List<Class> getPackageClasses(String packageName) {
        List<Class> classList = new ArrayList<>();
        //获取包的名字 并进行替换
        String packageDirName = packageName.replace('.', '/');
        try {
            URL url = Thread.currentThread().getContextClassLoader()
                    .getResources(packageDirName).nextElement();
            String filePath = URLDecoder.decode(url.getFile(),"utf-8");
            File dirFile = new File(filePath);
            String[] classFiles =  dirFile.list();
            for(String f : classFiles){
                if(f.endsWith(".class")) {
                    String fileName = f.substring(0,f.lastIndexOf(".class"));
                    Class c = Class.forName(packageName+"."+fileName);
                    classList.add(c);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return classList;
    }


    public static void main(String[] args) {
        new MainServer();
    }
}
